import gconf
import gobject
import gtk
import os

from settings import Settings

class Preferences:
    
    def __init__(self, window, widgets):
        self.window = window
        self.window.connect("response",self.response_handler)
        self.window.connect("delete_event", self.on_delete_event)
        self.window.connect("show", self.update_ui)

        self.widgets = widgets

        self.settings = Settings()
        self.settings.client.notify_add(self.settings.path, self.update_ui)

        # Fill the theme combobox
        self.thememodel = gtk.ListStore(str)

        for dir in os.listdir("."):
            if os.path.exists(os.path.join(dir,"bg.svg")):
                self.thememodel.append([dir])

        self.widgets["theme"].set_model(self.thememodel)

        # Fill control table
        self.controlmodel = gtk.TreeStore(str, str, bool)
        
        for control in self.settings.controls:
            self.controlmodel.append(None, [control, "", True])

        self.widgets["control"].set_model(self.controlmodel)

        renderer = gtk.CellRendererText()
        column = gtk.TreeViewColumn(None, renderer, text=0)
        self.widgets["control"].append_column(column)

        renderer = gtk.CellRendererText()
        column = gtk.TreeViewColumn(None, renderer, text=1)
        self.widgets["control"].append_column(column)
        self.widgets["control"].set_enable_search(False)

        #renderer.connect("editing-started", self.start_editing)

        self.kh_id = None

        self.widgets["control"].connect("button_press_event",
            self.start_editing)

        self.update_ui()


    def start_editing_edit(self, cellrenderer, editable, path):
        self.iter = self.controlmodel.get_iter(path)
        self.oldval = self.controlmodel.get_value(self.iter, 1)
        editable.set_text("<Press a key>")
        editable.set_editable(False)
        editable.connect("editing-done", self.editing_done)


    def editing_done(self, celleditable):
        print "Editing done"
        return
        self.controlmodel.set_value(self.iter, 1, celleditable.get_text())
        

    def start_editing(self, control, event):
        if event.type == gtk.gdk._2BUTTON_PRESS:
            self.done_editing()

            path = self.widgets["control"].get_path_at_pos(int(event.x),
                int(event.y))

            self.iter = self.controlmodel.get_iter(path[0])
            self.prevval = self.controlmodel.get_value(self.iter, 1)
            self.controlmodel.set_value(self.iter, 1, "<Press a key>")
            
            self.kh_id = self.widgets["control"].connect("key_press_event",
                self.get_key_pressed)


    def get_key_pressed(self, controlwidget, event):
        if event.keyval == gtk.keysyms.Escape:
            self.done_editing()
            return True
            
        val_str = gtk.gdk.keyval_name(event.keyval)

        self.controlmodel.set_value(self.iter, 1, val_str) 

        self.widgets["control"].disconnect(self.kh_id)
        self.kh_id = None

        return True


    def done_editing(self):
        if self.kh_id is not None:
            self.widgets["control"].disconnect(self.kh_id)
            self.kh_id = None
            self.controlmodel.set_value(self.iter, 1, self.prevval)
        

    def on_delete_event(self, widget, event):
        self.window.response(gtk.RESPONSE_CANCEL)
        return True


    def response_handler(self, widget, rid):
        self.done_editing()

        if rid == gtk.RESPONSE_CANCEL:
            widget.hide()

        elif rid == gtk.RESPONSE_APPLY:
            self.export_gconf()

        elif rid == gtk.RESPONSE_OK:
            self.export_gconf()
            widget.hide()


    def export_gconf(self):
        self.settings.set("setup/starting_level", 
            self.widgets["starting_level"].get_value_as_int())

        self.settings.set("gameplay/shadow",
            self.widgets["shadow"].get_active())

        self.settings.set("gameplay/random_colours", 
            self.widgets["random_colours"].get_active())

        self.settings.set("theme/theme", 
            self.widgets["theme"].get_active_text())

        for i in range(0, len(self.settings.controls)):
            value = gtk.gdk.keyval_from_name(self.controlmodel[i][1])
            self.settings.set("control/" + self.settings.controls[i], value)
        
    
    def update_ui(self, cnxn_id=None, entry=None, *user_data):
        self.widgets["starting_level"].set_value(\
            self.settings.value("setup/starting_level"))

        self.widgets["shadow"].set_active(\
            self.settings.value("gameplay/shadow"))

        self.widgets["random_colours"].set_active(\
            self.settings.value("gameplay/random_colours"))
        
        # Set the current theme in the drop-down list to the one in gconf
        theme = self.settings.value("theme/theme")

        i = 0
        for row in self.thememodel:
            if row[0] == theme:
                self.widgets["theme"].set_active(i)
                break
            i += 1

        # Fill the keyboard controls model with the values from gconf
        for i in range(0, len(self.settings.controls)):
            value = self.settings.value("control/" + self.settings.controls[i])
            value = gtk.gdk.keyval_name(value)
            iter = self.controlmodel.get_iter(i)
            self.controlmodel.set_value(iter, 1, value)


